<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 警示框 -->
      <el-alert title="添加商品信息" type="info" show-icon :closable="false" center></el-alert>
      <!-- 这里用到了步骤条 -->
      <!-- :active绑定的是数字 -->
      <el-steps :space="200" :active="+activeTabNum" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 侧边是tab栏，把tab栏放在一个表单里方便获取 -->
      <!-- 以通过tabs的v-model实现联动 -->
      <!-- before-leave切换标签之前的钩子，若返回 false 或者返回 Promise 且被 reject，则阻止切换。 -->
      <el-form label-position="top" ref="baseInfoRef" :model="baseInfoForm" :rules="rules">
        <el-tabs
          tab-position="left"
          v-model="activeTabNum"
          :before-leave="checkBefore"
          @tab-click="controlData"
        >
          <el-tab-pane label="基本信息" name="0">
            <!-- 基本信息 -->
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="baseInfoForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model.number="baseInfoForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model.number="baseInfoForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model.number="baseInfoForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <!-- 级联选择器 -->
              <el-cascader
                :options="goodsCateList"
                clearable
                v-model="baseInfoForm.goods_cat"
                :props="selectCateProp"
                @change="checkCateLength"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 根据基本信息中选择的商品分类中的三级分类id获取分类参数 -->
            <el-form-item v-for="item in paramsList" :key="item.attr_id" :label="item.attr_name">
              <!--双向数据绑定，取消勾选，paramsList中的也会消失 v-model="item.attr_vals"为数组，值对应label的值 -->
              <el-checkbox-group v-model="item.attr_vals2">
                <!-- 复选框 -->
                <el-checkbox
                  v-for="(i1,i) in item.attr_vals"
                  :key="i"
                  border
                  :label="i1"
                  v-show="i1"
                  size="mini"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              v-for="item in attributesList"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <!-- 双向数据绑定，取消勾选，attributesList中的也会消失 v-model="item.attr_vals"为数组，值对应label的值 -->
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-form-item>
              <!-- 图片上传 -->
              <!-- action图片上传地址,之前axios请求拦截器设置了请求头，但是这里没有，还需处理携带token的问题，有个属性header可以设置请求头 -->
              <!-- 另外监听上传的结果，将返回结果绑定到表单对象中 -->
              <el-upload
                action="http://127.0.0.1:8888/api/private/v1/upload"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                list-type="picture"
                :headers="requestHeader"
                :on-success="addImgToForm"
              >
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器，在ui里安装依赖vue-quill-editor -->
            <el-form-item>
              <quill-editor
                ref="myQuillEditor"
                :options="editorOption"
                v-model="baseInfoForm.goods_introduce"
              />
            </el-form-item>
            <!-- 添加商品按钮 -->
            <el-button type="primary" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览对话框 -->
    <el-dialog title="图片预览" :visible.sync="imgDialogVisible" width="50%">
      <img :src="imgUrl" alt width="200" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="imgDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="imgDialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// lodash深拷贝依赖
import _ from 'lodash'
export default {
  data() {
    return {
      // 添加商品信息,把tab栏放在一个表单里方便获取
      baseInfoForm: {
        goods_name: '',
        goods_cat: [],
        goods_price: '',
        goods_weight: '',
        goods_number: '',
        goods_introduce: '',
        pic: [],
        attrs: []
      },
      rules: {
        goods_name: [
          { required: true, message: '商品名必填', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '商品价格必填', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '商品数量必填', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '商品重量必填', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '商品分类必填', trigger: 'blur' }
        ]
      },
      // 级联选择器
      goodsCateList: [],
      selectCateProp: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      // 通过v-model 的activeTabNum 钩子将tab和步骤条联动起来
      activeTabNum: '0',
      // 根据基本信息中选择的商品分类中的三级分类id获取分类参数
      paramsList: [],
      attributesList: [],
      // 处理图片上传请求头
      requestHeader: {
        Authorization: sessionStorage.getItem('login_token')
      },
      // 图片预览
      imgUrl: '',
      imgDialogVisible: false,
      editorOption: {}
    }
  },
  created() {
    this.getGoodsCateList()
  },
  methods: {
    async getGoodsCateList() {
      // 获取商品分类列表
      const { data: ret } = await this.$http.get('categories')
      if (ret.meta.status !== 200) return this.$message.error(ret.meta.msg)
      this.goodsCateList = ret.data
    },
    checkBefore(num1, num2) {
      // before-leave钩子
      let flag
      this.$refs.baseInfoRef.validate(val => {
        if (!val) {
          this.$message({
            message: '请输入完整信息',
            type: 'error',
            duration: 1000
          })
          flag = false
        } else {
          flag = true
        }
      })
      return flag
      // if (num2 === '0' && this.baseInfoForm.goods_cat.length !== 3) {
      //   this.$message.error('请选择商品分类')
      //   return false
      // }
    },
    checkCateLength() {
      // 检查商品商品分类，只允许选中三级，不然要清空baseInfoForm中的 goods_cate
      if (this.baseInfoForm.goods_cat.length !== 3) {
        return (this.baseInfoForm.goods_cat = [])
      }
      // 选择变化时
      this.getGoodsParams('many')
      this.getGoodsParams('only')
    },
    controlData() {
      // tab栏切换时触发
      if (this.activeTabNum === '1') {
        if (this.paramsList.length) return
        this.getGoodsParams('many')
      } else if (this.activeTabNum === '2') {
        if (this.attributesList.length) return
        this.getGoodsParams('only')
      }
    },
    async getGoodsParams(sel) {
      const { data: ret } = await this.$http.get(
        `categories/${this.cateID}/attributes`,
        {
          params: { sel }
        }
      )
      if (ret.meta.status !== 200) return this.$message.error(ret.meta.msg)
      if (sel === 'many') {
        ret.data.forEach(item => {
          item.attr_vals = item.attr_vals.split(',')
          item.attr_vals2 = []
        })
        this.paramsList = ret.data
        console.log('动态参数列表', this.paramsList)
      } else {
        this.attributesList = ret.data
        console.log('静态属性列表', this.attributesList)
      }
    },
    handleRemove(file, fileList) {
      // 处理移除图片
      console.log(file)
      // 根据临时路径找索引
      const img = file.response.data.tmp_path
      console.log(img)
      const index = this.baseInfoForm.pic.findIndex(item => item.pic === img)
      console.log(index)
      this.baseInfoForm.pic.splice(index, 1)
    },
    handlePreview(file) {
      // 点击图片名预览图片,显示预览对话框
      console.log(file)
      this.imgUrl = file.url
      this.imgDialogVisible = true
    },
    addImgToForm(response, file, fileList) {
      // 监听图片上传的结果，将返回结果绑定到表单对象中
      console.log(response)
      this.baseInfoForm.pic.push({ pic: response.data.tmp_path })
      console.log(this.baseInfoForm)
    },
    async addGoods() {
      // 添加商品
      // 由于上传数据good_cat需要的是字符串，而v-model需要绑定的数据，如果直接join转换会报错,做个深拷贝，有个依赖叫lodash
      const cloneForm = _.cloneDeep(this.baseInfoForm)
      cloneForm.goods_cat = cloneForm.goods_cat.join(',')
      // 同时遍历paramsList和attributesList获取 attrs
      console.log(this.paramsList)
      this.paramsList.forEach(item => {
        cloneForm.attrs.push({
          attr_id: item.attr_id,
          attr_value: item.attr_vals2
        })
      })
      this.attributesList.forEach(item => {
        cloneForm.attrs.push({
          attr_id: item.attr_id,
          attr_value: item.attr_vals
        })
      })
      console.log(cloneForm)
      const { data: ret } = await this.$http.post('goods', cloneForm)
      if (ret.meta.status !== 201) return this.$message.error(ret.meta.msg)
      this.$message.success(ret.meta.msg)
      // 创建完返回商品列表页
      this.$router.push('/goods')
    }
  },
  computed: {
    cateID() {
      return this.baseInfoForm.goods_cat[this.baseInfoForm.goods_cat.length - 1]
    }
  }
}
</script>

<style lang='less' scoped>
.el-steps {
  margin: 15px 0;
}
.el-checkbox {
  margin-right: 10px;
  margin-top: 10px;
  margin-left: 0 !important;
}
</style>
